package com.urbo.android.shortcutter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;


public class GridDialog {
	
	private AlertDialog gridDialog;				// Dialog to show
	private View gridDialogLayout;
	private GridView thisGridView;
	private Context context;
	private ResImageAdapter imageAdapter; 
	private ResImageAdapter.IconCache listOfImages; //List of availabel icons. <packagename, id_of_resource>
	private ProgressDialog busyDialog;
	
	// Click listener. Listener wrapper for GridView OnItemClick of this dialog
	private OnClickListener onClickListener = null;
		
	// Interface for gridDialog.OnClickListener
	public interface OnClickListener {
		public abstract void onClick(Drawable d);
	}
		
	// OnClickListener setter
	public void SetOnClickListener(OnClickListener listener) {
		onClickListener = listener;
	}
		
	// Internal click called from ListView OnItemClickListener of this dialog. Call ListSelectionDialog.OnClickListener
	private void click(Drawable d) {
		if (onClickListener != null) {
			onClickListener.onClick(d);
		}
	}
		
	// public ListSelectionDialog(Context context, ListView.OnClickListener dialogClickListener){
	public GridDialog(Context context) {
		this.context = context;
		listOfImages = new ResImageAdapter.IconCache();
		createGridDialog();
		attachAdapter();
		thisGridView.setOnItemClickListener(onItemClickListener);
	}

	// 
	public Map<String,String> createIconItem(String packageName, String resourceId){  

	    Map<String,String> item = new HashMap<String,String>();  
	    item.put(ResImageAdapter.ITEM_PACKAGE_NAME, packageName);
	    item.put(ResImageAdapter.ITEM_RESOURCE_ID, resourceId);
	    return item;  
	}
	
	// Attach image adapter
	private void attachAdapter() {
		imageAdapter = new ResImageAdapter(context, listOfImages, R.layout.icon_grid_item, R.id.icon_grid_item);
		thisGridView.setAdapter(imageAdapter);
	}
	
	// Internal dialog builder
	private void createGridDialog() {//DialogInterface.OnClickListener dialogClickListener) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		gridDialogLayout = inflater.inflate(R.layout.icons_grid, null);
		thisGridView = (GridView)gridDialogLayout.findViewById(R.id.icon_grid_view);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(gridDialogLayout);
		gridDialog = builder.create();
	}	
	
	// Handler for click on item of GridView
	public AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg, View view, int position,long id) {
			ImageView iv = (ImageView) view.findViewById(R.id.icon_grid_item);
			click(iv.getDrawable());
		}
	};

	private Handler messageHandler = new Handler() {	
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			busyDialog.dismiss();
			imageAdapter.notifyDataSetChanged();
			gridDialog.show();
		}
	};
	
	private void receiveIpkgIcons(final String ipkgName, final Bundle icons) {
		
		this.busyDialog = ProgressDialog.show(context, "", "Retrieving list of icons", true);
		
		// before new list of icons is loaded, old list must be cleared
		imageAdapter.clear();
		
		new Thread() {
			public void run() {
				try {
    				for ( String pname : icons.keySet() ) {
    					listOfImages.put( context, ipkgName, (Integer)icons.get(pname) );
    				}
				}
				catch(Exception e) {}
				messageHandler.sendEmptyMessage(0);
			}
		}.start();
	}
	
	private void receiveApplicationIcons(final List<PackageInfo> packs) {
		
		this.busyDialog = ProgressDialog.show(context, "", "Retrieving list of icons", true);
		
		// before new list of icons is loaded, old list must be cleared
		imageAdapter.clear();
		
		new Thread() {
			public void run() {
				try {
				    for(int i=0;i<packs.size();i++) {
			        	PackageInfo p = packs.get(i);
			        	if ((Integer)p.applicationInfo.icon > 0) {
			        			listOfImages.put( context, p.packageName, (Integer)p.applicationInfo.icon );
			        	} 
			        }
				}
				catch(Exception e) {}
				
				messageHandler.sendEmptyMessage(0);
			}
		}.start();
	}

	public void setIpkgIconSource(final String ipkgName) {
		
		context.sendOrderedBroadcast(
	    		new Intent( IpackKeys.Actions.QUERY_ICONS ).setComponent(
	    				new ComponentName(
	    						ipkgName,	
	    						ipkgName + "." + IpackKeys.RECEIVER_NAME
	    				)
	    		),
	    		null, // receiver permission
	    		new BroadcastReceiver() {
	    			public void onReceive( Context c, Intent i ) {
	    				receiveIpkgIcons(ipkgName, getResultExtras( true ));
	    			}
	    		},
	    		null,
	    		Activity.RESULT_OK,
	    		null,
	    		null
	   	);
	}
	public void setAplicationIconSource() {
		
        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packs = packageManager.getInstalledPackages(0);
        receiveApplicationIcons(packs);
	}
	
	public void show() {
		gridDialog.show();
	}
	
	public void dismiss() {
		gridDialog.dismiss();
		imageAdapter.clear();
		imageAdapter.notifyDataSetChanged();
	}
}
		

